package gr.atc.epart;

import gr.atc.epart.actions.Action;
import gr.atc.epart.actions.ActionComment;
import gr.atc.epart.actions.Deliberation;
import gr.atc.epart.googlewrapper.GoogleServiceCallbackType;
import gr.atc.epart.googlewrapper.accounts.GoogleAccountManager;
import gr.atc.epart.googlewrapper.accounts.GoogleLoginDialog;
import gr.atc.epart.googlewrapper.moderator.GoogleModerator;
import gr.atc.epart.googlewrapper.moderator.ModeratorSeries;
import gr.atc.epart.googlewrapper.moderator.ModeratorSubmission;
import gr.atc.epart.googlewrapper.moderator.ModeratorTopic;
import gr.atc.epart.googlewrapper.moderator.ModeratorVote;
import gr.atc.epart.googlewrapper.youtube.YouTubeVideoComment;
import gr.atc.epart.googlewrapper.youtube.YouTubeVideoEntry;
import gr.atc.epart.net.RetrievalFailedException;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

public class DeliberationTopicsActivity extends ListActivity {
	private static final int ADD_TOPIC = 0;

	private static final int DIALOG_LOGIN_INPUT = 0;
	private static final int DIALOG_LOGIN_FAILED = 1;

	private GoogleModerator _moderator;
	int _moderatorSeriesId;

	ModeratorSeries _series;

	private DeliberationTopicsAdapter _adapter;
	ProgressDialog _progressDialog;

	ModeratorTopic _selectedTopic;
	GoogleAccountManager _accountManager;

	private class OnGoogleLoginDialogHandler implements
			GoogleLoginDialog.OnCompleteListener {

		@Override
		public void cancel() {
			// return to the previous activity.
			DeliberationTopicsActivity.this.finish();
		}

		@Override
		public void login(String username, String password) {
			showProgressDialog();
			_moderator.authenticate(username, password);
		}
	}

	//
	// used to receive callbacks
	//
	private Handler _messageHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {

			case GoogleServiceCallbackType.UserAuthenticationRequired: {
				// display a dialog to receive the password....the username is
				// known..!

				dismissProgessDialog();

				String username = _accountManager.getAccountEmail();

				GoogleLoginDialog logindialog = new GoogleLoginDialog(
						DeliberationTopicsActivity.this,
						"Please login into Google Moderator", username,
						new OnGoogleLoginDialogHandler());
				logindialog.show();

				// _moderator.authenticate("tsakonas.nick@gmail.com","m4l4k13$");
			}
				break;

			case GoogleServiceCallbackType.ModeratorServiceIsReady:
				// use this series id for test
				// _moderator.getSeries(140091);
				_moderator.getSeries(_moderatorSeriesId);

				// _moderator.getSeries("http://www.google.com/moderator/#15/e=2233b");
				// _moderator.getSeries("http://www.google.com/moderator/#16/e=21ee4");
				break;

			case GoogleServiceCallbackType.ModeratorSeriesReceived:

				ArrayList<ModeratorSeries> seriesList = (ArrayList<ModeratorSeries>) msg
						.getData().getSerializable("SERIES");

				if (seriesList == null) {
					// error...cannot retrieve series
					this
							.sendEmptyMessage(GoogleServiceCallbackType.OperationError);
					// showErrorRetrievingSeriesAlert() ;
					// dismissProgessDialog();
				} else {
					// the list is used for future use...in order to retrieve
					// more than one series at a time
					// at the moment only one series is contained
					_series = seriesList.get(0);

					if (_series != null) {
						if (_series.shouldRetrieveTopics())
							_moderator.getTopics(_series);
						else
							dismissProgessDialog(); // stop the progress dialog

					} else {
						this
								.sendEmptyMessage(GoogleServiceCallbackType.OperationError);
					}
				}

				break;

			case GoogleServiceCallbackType.ModeratorSeriesTopicsReceived:

				ArrayList<ModeratorTopic> topics = (ArrayList<ModeratorTopic>) msg
						.getData().getSerializable("TOPICS");

				// display the topics
				_adapter.setTopics(topics);

				// stop the progress dialog
				dismissProgessDialog();

				break;

			case GoogleServiceCallbackType.OperationError:
				// _ownerCallback.sendMessage(msg);

				/*
				 * 
				 * Message seriesMessage = new Message(); seriesMessage.what =
				 * GoogleServiceCallbackType.ModeratorSeriesReceived;
				 * 
				 * Bundle bundle = new Bundle();
				 * bundle.putSerializable("SERIES", seriesList);
				 * 
				 * seriesMessage.setData(bundle);
				 * _ownerCallback.sendMessage(seriesMessage);
				 */
			{
				if (msg.getData() != null) {
					String error = msg.getData().getString("DESCRIPTION");
					showErrorAlert("Google moderator error:" + error);
					
				}
				dismissProgessDialog();
			}
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle icicle) {

		super.onCreate(icicle);
		setContentView(R.layout.topicslist);

		_accountManager = new GoogleAccountManager(this);

		//
		// retrieve all the topics for the specified series
		//
		Deliberation selectedDeliberation = (Deliberation) EPartVolatileDataStore
				.getInstance().getSelectedAction();
		_moderatorSeriesId = selectedDeliberation.getModeratorSeriesId();

		// the topics are not available yet....
		_adapter = new DeliberationTopicsAdapter(this);
		setListAdapter(_adapter);

		showProgressDialog();

		//
		// start google moderator
		//
		try {
			_moderator = new GoogleModerator(_messageHandler);
			//
			// try to authenticate (IF there are previous credentials present)
			//
			_moderator.authenticate();

		} catch (Exception e) {
			dismissProgessDialog();
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		// EPartVolatileDataStore.getInstance().setModeratorInstance(_moderator);

		_selectedTopic = (ModeratorTopic) _adapter.getItem(position);
		EPartVolatileDataStore.getInstance().setModeratorTopic(_selectedTopic);

		EPartVolatileDataStore.getInstance().setModeratorAuthToken(
				_moderator.getAuthToken());

		try {
			Intent topicSubmissionsIntent = new Intent();
			topicSubmissionsIntent.setClassName("gr.atc.epart",
					"gr.atc.epart.DeliberationSubmissionActivity");

			// topicSubmissionsIntent.putExtra("package gr.atc.epart.submisions",submisions
			// );

			startActivity(topicSubmissionsIntent);

		} catch (Exception e) {
			Log.i("DeliberationTopicsActivity", e.getMessage());
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(Menu.NONE, ADD_TOPIC, Menu.NONE, "Add Topic");

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case ADD_TOPIC:

			String username = AccountUtil.getAccountName(this.getBaseContext());
			ArrayList<ModeratorTopic> topicList = _series.getTopicList();
			
			
			if (topicList.size() > 0) 
			{
				String seriesOwner = topicList.get(0).getPresenter();
			
				Log.i("DeliberationTopicsActivity", "username: " + username);
				Log.i("DeliberationTopicsActivity", "seriesOwner: " + seriesOwner);

				if (!username.equals(seriesOwner)) {
					createAlertFailure("You have to be the owner of this series to add topics");
					return false;
				}
			}
			
			// set the current series we are working on. this is where the new
			// topic will be attached
			EPartVolatileDataStore.getInstance().setModeratorSeries(_series);
			EPartVolatileDataStore.getInstance().setModeratorAuthToken(
					_moderator.getAuthToken());
			Intent viewDeliberationsTopicsIntent = new Intent();
			viewDeliberationsTopicsIntent.setClassName("gr.atc.epart",
					"gr.atc.epart.DeliberationAddTopicActivity");
			startActivityForResult(viewDeliberationsTopicsIntent, ADD_TOPIC);
			return true;

		default:
			return false;
		}

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case Activity.RESULT_OK:
			if (requestCode == ADD_TOPIC) {
				// a new submission was made
				// Although the response is parsed to a new topic object,
				// I cannot pass it back to this activity...
				// so,I can only retrieve again the topics of the current series
				// in order to update the list
				// stupid, but it is my only way at the moment

				// NOTE : this call is asynchronous...
				// NOTE2: the method intention is to append topics, so we have
				// to remove the existing ones before calling it
				showProgressDialog();

				_series.removeAllTopics();
				_moderator.getTopics(_series);

			}
			break;
		default:
			break;
		}
	}

	public void createAlertFailure(String msg) {

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setMessage(msg);
		dlgAlert.setTitle("Action Denied");
		dlgAlert.setPositiveButton("OK", null);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}

	private void showProgressDialog() {

		_progressDialog = new ProgressDialog(this);
		_progressDialog.setMessage("Please wait...");
		_progressDialog.setIndeterminate(true);
		_progressDialog.setCancelable(false);
		_progressDialog.show();
	}

	public void showErrorAlert(String msg) {

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setMessage(msg);
		dlgAlert.setTitle("Error");
		dlgAlert.setPositiveButton("OK", null);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}

	private void dismissProgessDialog() {
		_progressDialogHandler.sendEmptyMessage(0);
	}

	// Define the Handler that receives messages from the thread and update the
	// progress
	final Handler _progressDialogHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (_progressDialog != null)
				_progressDialog.dismiss();

		}
	};

}
